package com.xuan.web;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

@WebServlet(urlPatterns = "/GetSmsCodeAction")
public class GetSmsCodeAction extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = getCode(req.getParameter("mob"));
        req.getSession().setAttribute("code",code);
        req.getRequestDispatcher("findPassword.jsp").forward(req,resp);
    }

    public String getCode(String mob){
        HashMap<String, Object> result = null;
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        restAPI.init("app.cloopen.com", "8883");
        // 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883.
        restAPI.setAccount("8aaf07087d27f73a017d2c2013a200ab", "4c04653fb2014342995e938b4d4619c2");
        // 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在控制首页中看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN。
        restAPI.setAppId("8aaf07087d27f73a017d2c2014e100b2");
        // 请使用管理控制台中已创建应用的APPID。
        String code = String.valueOf(Math.random()).substring(2, 8);
        System.out.println("验证码"+code);
        result = restAPI.sendTemplateSMS(mob,"1" ,new String[]{code,"30分钟"});
        System.out.println("SDKTestGetSubAccounts result=" + result);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
        return code;
    }
}
